import label from '../../api/label'
import * as types from '../mutation-types.js'

const state = {
  labelData: [],
  notice: [],
  labelErr: []
}

const getters = {
  labelData: state => state.labelData,
  notice: state => state.notice,
  labelErr: state => state.labelErr
}

const actions = {
  getLabelDatas ({commit}, {page}) {
    return new Promise((resolve, reject) => {
      label.getLabelDatas(page)
        .then(data => {
          commit(types.GET_LABELDATA, data)
          resolve()
        })
        .catch(err => {
          commit(types.ERR_LABEL, err)
        })
    })
  },
  deleteLabel ({commit, dispatch}, {labelId}) {
    return new Promise((resolve, reject) => {
      label.deleteLabel(labelId)
        .then(data => {
          commit(types.LABEL_NOTICE, '删除标签成功')
          dispatch('getLabelDatas', {page: 1})
          resolve()
        })
        .catch(err => {
          commit(types.ERR_LABEL, err)
        })
    })
  },
  addLabel ({commit, dispatch}, tags) {
    return new Promise((resolve, reject) => {
      label.addTags(tags)
        .then(data => {
          commit(types.LABEL_NOTICE, '添加标签成功')
          dispatch('getLabelDatas', {page: 1})
          resolve()
        })
        .catch(err => {
          commit(types.ERR_LABEL, err)
        })
    })
  }
}

const mutations = {
  [types.GET_LABELDATA] (state, data) {
    state.labelData = data
  },
  [types.LABEL_NOTICE] (state, data) {
    console.log('mutation', data)
    state.notice.push({msg: data})
  },
  [types.ERR_LABEL] (state, err) {
    state.labelErr.push({msg: err})
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
